import InfoWindow from '@/components/InfoWindow';
// import AMapLoader from '@amap/amap-jsapi-loader';
import '@amap/amap-jsapi-types';
import type { RefObject } from 'react';
import { useEffect, useRef, useState } from 'react';
import type { OverviewParkingLots, ParkingLotInfo } from '../types';
import './index.less';
// import { getVisualOverview } from '../service';
const { AMap } = window;
let map: AMap.Map;
function MapContainer(props: {
  parkingLots: OverviewParkingLots[];
  onCenterChange: (center: [number, number]) => void;
}) {
  // (window as any)._AMapSecurityConfig = {
  //   securityJsCode: '0fcf9869284dccadd71a465f8f1fe8f6',
  // };
  //@ts-ignore
  const { parkingLots, onCenterChange } = props;
  // const [_map, setMap] = useState<AMap.Map>();
  //@ts-ignore
  // const [amap, setAmap] = useState<AMap>();
  const defaultItem: ParkingLotInfo = {
    parkingType: '路内停车场',
    parkingName: '',
    totalSpace: 0,
    lastSpace: 0,
    occupySpace: 0,
    imgs: [],
  };
  // const [center, setCenter] = useState<[number, number]>([120.384, 30.344]); //坐标点击的点击位置 （纬度取决
  const [isShowInfoWindow, setIsShowInfoWindow] = useState<boolean>(true);
  const [show, setShow] = useState<string>('none');
  const [infoNow, setInfoNow] = useState<ParkingLotInfo>(defaultItem);
  const [markers, setMarkers] = useState<any[]>([]);
  const infoWindow: RefObject<HTMLDivElement> = useRef<HTMLDivElement>(null);

  const setInfoWindow = (position: any) => {
    // console.log(e);
    const point = new AMap.LngLat(position.lng, position.lat);
    console.log(point);
    const content = infoWindow.current;
    if (content) {
      const infoShowWindow = new AMap.InfoWindow({
        isCustom: true, //使用自定义窗体
        content, //传入 dom 对象，或者 html 字符串
        // offset: new AMap.Pixel(16, -50),
      });
      if (map) {
        infoShowWindow.open(map, [point.getLng(), point.getLat()]);
        setShow('block');
        setIsShowInfoWindow(true);
        // _map.openInfoWindow(infoShowWindow, point);
      }
    }
  };
  const closeInfoWindow = () => {
    if (!map) return;
    map?.clearInfoWindow();
  };

  const createNewMarker = (data: {
    type: string;
    id: string;
    location: { lng: number; lat: number };
  }) => {
    if (!map) return;
    const color = data.type === 'one' ? 'green' : data.type === 'two' ? 'yellow' : 'orange';
    const marker = new AMap.Marker({
      position: [data.location.lng, data.location.lat],
      icon: new AMap.Icon({
        image: `/visual/${color}marker.svg`,
        size: new AMap.Size(32, 80),
        imageSize: new AMap.Size(32, 80),
      }),
    }); //创建一个新的marker
    // markers.push(marker);
    setMarkers([...markers, marker]);
    // const lnglat = marker.getPosition();
    // console.log(lnglat, '经纬度');
    marker.on('click', () => {
      // console.log(marker.getPosition());
      // console.log(data.id, '==>当前车场id');
      // console.log(parkingLots, '==>车场数据');
      const InfoItem = parkingLots.find((item) => item.parkingLotId === data.id);
      // console.log(InfoItem, '==>当前找到的item');
      if (InfoItem) {
        setInfoNow({
          ...infoNow,
          parkingName: InfoItem.parkingLotName,
          imgs: InfoItem.imgs,
          totalSpace: InfoItem.spotCount,
          lastSpace: InfoItem.spotCount - InfoItem.occupySpot,
          occupySpace: InfoItem.occupySpot,
        });
      }
      setInfoWindow(marker.getPosition());
      //@ts-ignore
      if (marker.getPosition()) {
        // map.setZoomAndCenter(
        //   16,
        //   //@ts-ignore
        //   new AMap.LngLat(marker.getPosition().getLat(), marker.getPosition().getLng()),
        // ); //重设map中的位置和zoom级别，并将位置点设置到marker的位);
      }
    });
    map.add(marker);
    return marker;
  };

  // const getLocation = async () => {
  //   navigator.geolocation.getCurrentPosition(
  //     function (position) {
  //       const latitude = position.coords.latitude;
  //       const longitude = position.coords.longitude;
  //       setCenter([Number(longitude), Number(latitude)]); //设置中心点位置
  //       console.log('经度：' + longitude + '，纬度：' + latitude);
  //     },
  //     function (error) {
  //       console.error('获取位置失败：' + error.message);
  //     },
  //   );
  // };

  // useEffect(() => {
  //   if (map) {
  //     onCenterChange(center);
  //     // getVisualOverview(...center).then((res) => {
  //     //   if (res.success) {
  //     //     console.log(res.data);
  //     //   }
  //     // });
  //   }
  //   // if (map) {
  //   //   //   console.log('设置中心了嘛');
  //   //   createNewMarker({ type: 'three', location: { lng: center[0], lat: center[1] } });
  //   //   map.setZoomAndCenter(16, center);
  //   // }
  // }, [center]);

  useEffect(() => {
    if (map) {
      map.remove(markers);
    }
    if (parkingLots.length) {
      parkingLots.forEach((item) => {
        const rate = item.occupySpot / item.spotCount;
        // console.log(rate)
        let type = 'one';
        if (rate < 0.5) {
          type = 'one';
        } else if (rate < 0.8) {
          type = 'two';
        } else {
          type = 'three';
        }
        createNewMarker({
          type,
          id: item.parkingLotId,
          location: { lng: item.location[0], lat: item.location[1] },
        });
      });
    }
  }, [parkingLots]);

  // useEffect(() => {
  //   createNewMarker({ type: 'three', location: { lng: center[0], lat: center[1] } });
  // }, [_map]);

  useEffect(() => {
    const getCenter = () => {
      const locationCenter: AMap.LngLat = map.getCenter();
      // console.log(locationCenter.getLng(), locationCenter.getLat());
      onCenterChange([locationCenter.getLng(), locationCenter.getLat()]);
      // if (locationCenter) {
      //   setCenter([120.372735, 30.303512]);
      //   // setCenter([locationCenter.getLng(), locationCenter.getLat()]);
      // }
    };
    const loadMap = () => {
      if (!AMap) return;
      map = new AMap.Map('map_container', {
        rotateEnable: false,
        pitchEnable: false,
        zoom: 16,
        pitch: 65,
        // showLabel: false,
        // rotation: 45,
        viewMode: '3D',
        mapStyle: 'amap://styles/darkblue',
        resizeEnable: true,
        zooms: [10, 20],
        skyColor: '#041f37',
      });
      map.setFeatures(['road', 'point', 'bg']);
      map.on('complete', () => {
        getCenter();
      });
      map.on('click', () => {
        // console.log('输出什么');
        closeInfoWindow();
      });
      map.on('moveend', getCenter);
      map.on('zoomend', getCenter);
      // setMap(map); // 实例化一个地图实例
    };
    loadMap();
    return () => {
      if (map) {
        map?.off('moveend', getCenter);
        map?.off('zoomend', getCenter);
      }
    };
  }, []);
  return (
    <>
      <div className="map" id="map_container" />
      {isShowInfoWindow ? (
        <div style={{ display: show }} ref={infoWindow}>
          <InfoWindow item={infoNow} close={closeInfoWindow} />
        </div>
      ) : (
        ''
      )}
    </>
  );
}

export default MapContainer;
